package cc.cocosky.imclient;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOInVoker {
	
	private static final String host = "127.0.0.1";
	private static final int port = 8899;
	private Application application = new Application();
	
	public void connect() throws IOException {
		InetSocketAddress address = new InetSocketAddress(host, port);
		Selector selector = Selector.open();
		SocketChannel channel0 = SocketChannel.open();
		channel0.configureBlocking(false);
		channel0.connect(address);
		channel0.register(selector, SelectionKey.OP_CONNECT);
		//如果不用Selector的方式，要循环执行finishConnect()判断，等待连接建立完成
//		while(!channel.finishConnect()) {
//			System.err.println("wait...\n");
//		}
		while(true) {
			selector.select();
			System.out.println("select");
			for(Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
				SelectionKey key = it.next();
				System.out.println("ops : " + key.readyOps());
				if(key.isReadable()) {
					SocketChannel channel = (SocketChannel)key.channel();
					Session session = application.getSession(channel);
					session.read();
				} else if(key.isConnectable()) {
					SocketChannel channel = (SocketChannel)key.channel();
					//用Selector的方式，不用循环执行，因为isConnectable()表示已满足连接的条件
					channel.finishConnect();
					application.createSession(channel);
					channel.register(selector, SelectionKey.OP_READ);
				}
				it.remove();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		NIOInVoker invoker = new NIOInVoker();
		invoker.connect();
	}

}
